﻿using System.Collections.Generic;
using System.Linq;

namespace ALDIOrganizer
{
    // A super-class which represents all rotas in the CurrentFile, as well as the _staff    
    public partial class DataFile
    {
        public delegate List<string> CopyThose(
            List<string> pAllTemplates,
            List<string> pAlreadyExistingTemplates);

        public void ImportTemplates(
            string pAnotherDataFile,
            CopyThose pCallBack)
        {
            var read = LoadFrom(pAnotherDataFile);
            if (read.Key != null)
            {
                throw read.Key; // rethrowing
            }
            var anotherDatafile = read.Value;
            if (!anotherDatafile.AnyChoiceOfTemplates)
            {
                return;
            }            
            var _all_templates = anotherDatafile.templates.Keys.ToList();
            _all_templates.Remove(Template.DefaultName);

            var _duplicate_templates = from _template in _all_templates
                                       where templates.Keys.Contains(_template)
                                       select _template;

            var _templates_to_import = pCallBack(
                _all_templates,
                _duplicate_templates.ToList());
            if (_templates_to_import == null)
            {
                return;
            }
            if(_templates_to_import.Count() == 0)
            {
                return;
            }
            foreach (var templateName in _templates_to_import)
            {
                var template = anotherDatafile.templates[templateName];
                if (templates.Keys.Contains(templateName)) // if we are overwriting an existing one with a different version of it...
                {
                    ReuniteWithDatabase(template);
                }
                else
                {
                    templates.Add(templateName, template);
                }
            }            
            if(OnTemplatesCollectionModified != null)
            {
                OnTemplatesCollectionModified();
            }
        }

    }
}
